package com.example.job;

import com.example.domain.Library;
import com.example.domain.OperationLog;
import com.example.mapper.LibraryMapper;
import com.example.service.LibraryService;
import com.example.service.OperationLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@Transactional
public class LibraryStatusService {
    
    @Autowired
    private LibraryMapper libraryMapper;

    @Autowired
    private OperationLogService operationLogService;
    
    // 每隔5分钟执行一次
    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void updateLibraryStatus() {
        LocalTime currentTime = LocalTime.now();
        List<Library> libraries = libraryMapper.selectList(null);
        // 需要更新的库存信息
        List<Library> updatedLibraries = new ArrayList<>();

        libraries.forEach(
                library -> {
                    if (shouldBeOpen(library, currentTime) && library.getLibraryStatus() != 2) {
                        library.setLibraryStatus(1);
                        updatedLibraries.add(library);
                        // 记录系统操作日志
//                        operationLogService.recordLog(null, library.getId(), 1, "开馆");
                        log.info("开馆：{}", library.getName());
                    }else if (shouldBeClosed(library, currentTime) && library.getLibraryStatus() != 2){
                        library.setLibraryStatus(0);
                        updatedLibraries.add(library);
                        // 记录系统操作日志
                        log.info("闭馆：{}", library.getName());
                    }
                }
        );

        if (updatedLibraries.isEmpty()) {
            log.info("库存信息没有更新");
        }
        updatedLibraries.forEach(library -> libraryMapper.updateById(library));
    }
    
    private boolean shouldBeOpen(Library library, LocalTime currentTime) {
        return currentTime.isAfter(library.getDailyOpenTime()) &&
               currentTime.isBefore(library.getDailyCloseTime()) &&
               library.getLibraryStatus() == 0;
    }
    
    private boolean shouldBeClosed(Library library, LocalTime currentTime) {
        return (currentTime.isAfter(library.getDailyCloseTime()) ||
                currentTime.isBefore(library.getDailyOpenTime())) &&
               library.getLibraryStatus() == 1;
    }
}